package com.skyline.wizard.task;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.lucene.document.Document;
import org.springframework.beans.factory.annotation.Autowired;

import com.skyline.wizard.dao.DocDao;
import com.skyline.wizard.dao.SeUpdateDao;
import com.skyline.wizard.indexer.Indexer;
import com.skyline.wizard.searcher.Searcher;

public class BaseUpdateTask {
	
	@Autowired
	private DocDao docDao;

	@Autowired
	private SeUpdateDao seUpdateDao;

	public void run(Log logger, int seDocType, Boolean updateNewDoc, Boolean updateUpdatedDoc, Boolean updateDeletedDoc,Indexer indexer) {

		Date lastUpdateTime = seUpdateDao.queryLastUpdateTime(seDocType);

		/**
		 * 更新新增加的记录
		 */
		if (updateNewDoc == true) {
			List<Document> docs = docDao.queryAllNewDocument(lastUpdateTime, seDocType);
			indexer.addDocuments(docs);
			logger.debug("update: add " + docs.size() + " new documents");
		}

		/**
		 * 更新刚被修改的记录
		 */
		if (updateUpdatedDoc == true) {
			List<Document> docs = docDao.queryAllUpdatedDocument(lastUpdateTime, seDocType);
			indexer.modifyDocuments(docs);
			logger.debug("update: update " + docs.size() + " updated documents");
		}

		/**
		 * 更新刚被删除的记录
		 */
		if (updateDeletedDoc == true) {
			List<Document> docs = docDao.queryAllDeletedDocument(lastUpdateTime, seDocType);
			indexer.deleteDocuments(docs);
			logger.debug("update: delete " + docs.size() + " deleted documents");
		}
		
		indexer.optimize();

		/**
		 * 更新最后更新时间lastUpdateTime
		 */
		seUpdateDao.updateLastUpdateTime(seDocType);
		
	}
}
